package com.yang.drawcard.image;

import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.core.click.IClick;
import com.core.ui.loader.LatteLoader;
import com.core.utils.dbtutil.DateUtil;
import com.core.utils.dbtutil.DbtLog;
import com.core.utils.dbtutil.JsonUtil;
import com.core.view.MyGridView;
import com.yang.drawcard.R;
import com.yang.drawcard.application.ConstValues;
import com.yang.drawcard.base.BaseActivity;
import com.yang.drawcard.book.domain.BookStc;
import com.yang.drawcard.image.adapter.ImageListAdapter;
import com.yang.drawcard.pic.PicsingleActivity;
import com.yang.drawcard.utils.ViewUtil;
import com.yang.drawcard.video.VideoService;
import com.yang.drawcard.video.adapter.SelectMonthAdapter;
import com.yang.drawcard.video.domain.MonthStc;

import java.lang.ref.SoftReference;
import java.util.ArrayList;
import java.util.Random;

import androidx.appcompat.widget.AppCompatTextView;
import de.hdodenhof.circleimageview.CircleImageView;

public class ImagePicActivity extends BaseActivity implements View.OnClickListener {

    private static final String TAG = "VideoActivity";

    private static final RequestOptions BANNER_OPTIONS = new RequestOptions()
            .diskCacheStrategy(DiskCacheStrategy.ALL)
            .dontAnimate()
            // .fitCenter()
            .centerCrop();

    private RelativeLayout backBtn;
    private RelativeLayout confirmBtn;
    private AppCompatTextView confirmTv;
    private CircleImageView backTv;
    private AppCompatTextView titleTv;


    private ArrayList<MonthStc> months;

    private GridView termCartLv;
    private ArrayList<BookStc> dataList;
    private ImageListAdapter adapter;


    private MyHandler handler;
    private VideoService service;

    private Random random;

    /**
     * 接收子线程消息的 Handler
     */
    public static class MyHandler extends Handler {

        // 软引用
        SoftReference<ImagePicActivity> fragmentRef;

        public MyHandler(ImagePicActivity fragment) {
            fragmentRef = new SoftReference<ImagePicActivity>(fragment);
        }

        @Override
        public void handleMessage(Message msg) {
            ImagePicActivity fragment = fragmentRef.get();
            if (fragment == null) {
                return;
            }
            Bundle bundle = msg.getData();

            // 处理UI 变化
            switch (msg.what) {
                case ConstValues.WAIT0://
                    fragment.postVideoListSuccess(bundle);
                    break;
            }
        }
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_imagepic);

        // 沉浸式
        setStatusBar();

        initView();
        initData();
    }

    private void initView() {

        backBtn = (RelativeLayout) findViewById(R.id.video_navigation_rl_back);
        confirmBtn = (RelativeLayout) findViewById(R.id.video_navigation_rl_confirm);
        confirmTv = (AppCompatTextView) findViewById(R.id.video_navigation_bt_confirm);
        backTv = (CircleImageView) findViewById(R.id.video_navigation_bt_back);
        titleTv = (AppCompatTextView) findViewById(R.id.video_navigation_tv_title);
        confirmBtn.setVisibility(View.VISIBLE);
        confirmBtn.setOnClickListener(this);
        backBtn.setOnClickListener(this);

        termCartLv = (GridView) findViewById(R.id.yd_imagepic_lv);

    }

    private void initData() {

        handler = new MyHandler(this);
        service = new VideoService(this, handler);
        random = new Random();

        titleTv.setText("图片列表");

        confirmTv.setText("所有");

        // 头像
        Glide.with(ImagePicActivity.this)
                .load(R.mipmap.ic_launcher_b)
                .apply(BANNER_OPTIONS)
                .into(backTv);

        dataList = new ArrayList<>();

        adapter = new ImageListAdapter(ImagePicActivity.this, dataList, new IClick() {
            @Override
            public void listViewItemClick(int position, View v) {

                BookStc book = dataList.get(position);

                switch (v.getId()) {
                    case R.id.item_imagelist_rl_pic://
                        if (ViewUtil.isDoubleClick(v.getId(), 1000))
                            return;

                        LatteLoader.showLoading(ImagePicActivity.this);
                        Intent picA = new Intent(ImagePicActivity.this, PicsingleActivity.class);
                        picA.putExtra("imageurl", book.getImageurl());//
                        startActivity(picA);

                        break;


                }
            }
        });

        termCartLv.setAdapter(adapter);


        // 请求book列表
        service.getVideoList(1834);

    }

    private void postVideoListSuccess(Bundle bundle) {

        String formjson = bundle.getString("formjson");
        String status = bundle.getString("status");

        if (ConstValues.SUCCESS.equals(status)) {

            dataList.clear();
            dataList.addAll((ArrayList<BookStc>) JsonUtil.parseList(formjson, BookStc.class));
            adapter.notifyDataSetChanged();
            termCartLv.setSelection(getRandomNum());

        } else {
            dataList.clear();
            adapter.notifyDataSetChanged();
        }
    }

    private int getRandomNum() {

        int currentDay = DateUtil.getCurrentDay();
        int randomNumber = 1;
        int sequence = 1;

        if (dataList.size() > 0) {
            int average = dataList.size() / 30;
            randomNumber = random.nextInt(average + 1);
            if (randomNumber == 0) {
                randomNumber = 1;
            }
            sequence = currentDay * randomNumber;
            if (sequence > dataList.size()) {
                sequence = dataList.size();
            }
        }

        return sequence;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.video_navigation_rl_back://
                if (ViewUtil.isDoubleClick(v.getId(), 2500))
                    return;

                //                Intent intent = new Intent(this, MineActivity.class);
                //                startActivityForResult(intent, 100);

                break;
            case R.id.video_navigation_rl_confirm:// 选择月份
                if (ViewUtil.isDoubleClick(v.getId(), 2500))
                    return;

                // LatteLoader.showLoading(BookActivity.this);
                // 弹窗选择月份
                // selectMonthData(months);

                break;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, final Intent data) {
        DbtLog.logUtils(TAG, "onActivityResult()-回调成功");
        super.onActivityResult(requestCode, resultCode, data);

        switch (requestCode) {

            case 100:// 修改密码返回
                initData();
                break;
        }
    }

    private AlertDialog dialog;
    View view;
    TextView title;
    TextView tv_cancle;
    MyGridView monthGv;

    // 弹窗选择月份
    private void selectMonthData(final ArrayList<MonthStc> months) {

        view = LayoutInflater.from(ImagePicActivity.this).inflate(R.layout.dialog_select_month, null);
        title = (TextView) view.findViewById(R.id.dialog_selectmonth_tv_title);
        tv_cancle = (TextView) view.findViewById(R.id.dialog_selectmonth_tv_cancle);
        monthGv = (MyGridView) view.findViewById(R.id.dialog_selectmonth_gv_month);

        dialog = new AlertDialog.Builder(ImagePicActivity.this).setCancelable(true).create();
        dialog.setView(view, 0, 0, 0, 0);

        SelectMonthAdapter adapter = new SelectMonthAdapter(ImagePicActivity.this, months);
        monthGv.setAdapter(adapter);

        monthGv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                MonthStc stc = months.get(position);
                confirmTv.setText(stc.getMonthname());
                service.getVideoList(position);
                dialog.dismiss();
            }
        });

        tv_cancle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });

        dialog.show();

        // 将对话框的大小按屏幕大小的百分比设置
        WindowManager windowManager = getWindowManager();
        if (windowManager != null) {
            Display display = windowManager.getDefaultDisplay();
            Window window = dialog.getWindow();// window
            window.setBackgroundDrawableResource(R.drawable.shape_solid_dialog);  //给AlertDialog设置4个圆角
            WindowManager.LayoutParams lp = window.getAttributes();
            lp.width = (int) (display.getWidth() * 0.72); //设置宽度
            // lp.height = (int) (display.getWidth() * 1.12); //设置高度
            // lp.height = (int) (display.getWidth() * 0.8); //设置高度
            window.setAttributes(lp);
        }

        LatteLoader.stopLoading();
    }


}
